#include <string>
#include "njs_screen_capture.h"
#include "api/video/video_render_manager.h"
#include "api/video/video_rotation.h"
#include "api/video/video_sink_interface.h"
#include "modules/video_capture/video_capture_defines.h"
#include "modules/video_capture/video_capture_factory.h"
#include "modules/video_capture/ohos/device_info_ohos.h"
#include "../rtc_log.h"

namespace ohosrtc {

NJSScreenCapture::NJSScreenCapture(int width, int height, int targetFps, webrtc::PeerConnectionFactoryInterface* pcFactoryPtr, rtc::Thread *worker_thread)
    : width_(width), height_(height), targetFps_(targetFps), screen_cap_wrap_(new webrtc::ScreenCapturerOhosWrap(pcFactoryPtr, worker_thread)) {
  RTC_LOG << "NJSScreenCapture init";
}

bool NJSScreenCapture::StartCapture() {
  screen_cap_wrap_->Init();
  screen_cap_wrap_->RegisterCaptureDataCallback(this);
  cricket::VideoFormat format;
  format.height = height_;
  format.width = width_;
  format.fourcc = 1;
  format.interval = 1000000000/targetFps_;
  screen_cap_wrap_->SetFrameRotation(webrtc::VideoRotation::kVideoRotation_0);
  auto res = screen_cap_wrap_->Start(format);
  return res;
}

void NJSScreenCapture::StopCapture() {
  screen_cap_wrap_->Stop();
  sinks_.clear();
}

void NJSScreenCapture::SetWindowOrientation(int orientation) {}
void NJSScreenCapture::SetSensorOrientation(int orientation) {}

void NJSScreenCapture::OnFrame(const webrtc::VideoFrame &frame) {
  for (const auto &listener : sinks_) {
    listener->OnFrame(frame);
  }
}

void NJSScreenCapture::BindPreviewRender(const std::string renderId) {
  auto renderSink = webrtc::VideoRenderManager::GetInstance()->GetRender(renderId);
  sinks_.emplace_back(std::move(renderSink));
}

void NJSScreenCapture::BindSink(std::shared_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>> sink) {
  sinks_.emplace_back(std::move(sink));
}

}